const express = require("express");
const router = express.Router();
//操作数据库封装
const query = require("../cfg/db").query;
//购物车列表
router.get("/api/car",async (req,res)=>{
    let sql = 'select * from tb_car';
    const {uid} = req.body;
    const r = await query(sql,[uid]);
    res.send({
        code:0,
        msg:'ok!',
        list:r
    });
})
//加入购物车
router.post("/api/car",async (req,res)=>{
    let sql = 'update tb_car set num=? where id=?';
    const {num,id} = req.body;
    const r = await query(sql,[num,id]);
    res.send({
        code:0,
        msg:'ok!'
    });
})
//加入购物车
router.put("/api/car",async (req,res)=>{
    let sql = 'insert into tb_car(uid,goodsname,price,pic,num) values (?,?,?,?,?)';
    const {uid,goodsname,url,pic,price} = req.body;
    const r = await query(sql,[uid,goodsname,price,url,1]);
    res.send({
        code:0,
        msg:'ok!'
    });
})
//商品列表
router.get("/api/goodslist",async (req,res)=>{
    let sql = 'select * from tb_goods';
    const r = await query(sql,[]);
    res.send({
        code:0,
        msg:'ok!',
        list:r
    });
})
//登录
router.post("/api/login",async(req,res)=>{
    let sql = "select * from tb_user where phone=? and password=?";
    //获取参数
    const {phone,password} = req.body;
    const r = await query(sql,[phone,password]);
    console.log(2222,r);
    if(r.length==0){
        res.send({
            code:1,
            msg:"用户名密码错误，重新输入！"
        });
    }else{
        res.send({
            code:0,
            msg:"ok！",
            info:{
                r
            }
        });
    }
})
//预留
router.post("/api/login2",(req,res)=>{
    const {phone,password} = req.body
    //链接数据库
    const mysql = require('mysql');
    //导入数据库配置信息
    const dbcfg = require('../cfg/dbcfg')

    const con = mysql.createConnection(dbcfg);
    con.connect(e=>{
        if(e){
            console.log("数据库链接错误:",e);
        }else{
            console.log("链接成功！");
            // 获取小程序参数
            let sql = "select * from tb_user where phone=? and password=?";
            con.query(sql,[phone,password],(e,r)=>{
                if(e){
                    console.log("数据错误",e);
                }else{
                    // console.log(r);
                    if(r.length==0){
                        res.send({
                            code:1,
                            msg:"用户名密码错误，重新输入！"
                        });
                    }else{
                        res.send({
                            code:0,
                            msg:"ok！",
                            info:{
                                r
                            }
                        });
                    }
                }
            })
        }
    })
})


module.exports = router;